<?php

namespace app\admin\extend\firebase;

use Firebase\JWT\JWT as FireBaseJwt;
use Firebase\JWT\Key;

class Jwt
{
    private string $key = 'lSp4BdED37L9Mnuj!N3Iw1hJCefye@Mh^hfqE!D2NRfCXjiShVtuZtKlAEcjTCcYshc';
    private int $expire = 43200;
    public string $error = '';

    //加密
    public function encrypt(array $data): string
    {
        $now = time();
        $payload = array(
            //'iss' => "http://example.org",       //jwt签发着
            //'aud' => "http://example.com",       //jwt所面向的用户
            'iat' => $now,                     //jwt签发时间
            //'nbf' => 1357000000,                 //定义在什么时间之前，某个时间点后才能访问
            'exp' => $now + $this->expire,                       //过期的时间
            'data' => $data                          //用户自定义信息
        );
        return FireBaseJwt::encode($payload, $this->key,'HS256');
    }

    //解密
    public function decrypt($token): bool|array
    {
        try {
            //FireBaseJwt::$leeway = 60;//当前时间减去60，把时间留点余地
            $decoded = FireBaseJwt::decode($token, new Key($this->key,'HS256')); //HS256方式，这里要和签发的时候对应
            return (array)$decoded;
        } catch(\Firebase\JWT\SignatureInvalidException $e) {  //签名不正确
            $this->error = '签名错误';
            return false;
        }catch(\Firebase\JWT\BeforeValidException $e) {  // 签名在某个时间点之后才能用
            $this->error = 'token尚未生效';
            return false;
        }catch(\Firebase\JWT\ExpiredException $e) {  // token过期
            $this->error = 'token过期';
            return false;
        }catch(\Exception $e) {  //其他错误
            $this->error = '非法token';
            return false;
        }
        //return FireBaseJwt::decode($token, $this->key, array('HS256'));
    }

}